//
//  LoginViewController.m
//  Gabber
//
//  Created by 陆惠国 on 11-8-24.
//  Copyright 2011年 恒生聚源. All rights reserved.
//

#import "LoginViewController.h"
#import "XMPPClient.h"

@implementation LoginViewController

@synthesize usernameField=_usernameField;
@synthesize passwordField=_passwordField;
@synthesize rememberMeSwitch=_rememberMeSwitch;
@synthesize versionLabel=_versionLabel;
@synthesize hostField=_hostField;
@synthesize portField=_portField;

#pragma mark - Init/dealloc
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[TTNavigator navigator] removeAllViewControllers];
        self.title = @"用户登录";
        self.variableHeightRows = YES;
        self.tableViewStyle = UITableViewStyleGrouped;

        //self.autoresizesForKeyboard = YES;
        
        if (TTIsPad()) {
            if (UIInterfaceOrientationIsLandscape(TTInterfaceOrientation())) {
                self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Landscape.png"]];
                self.tableView.frame = CGRectMake(400, 50, 400, 400);
            }else{
                self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Portrait.png"]];
                self.tableView.frame = CGRectMake(300, 200, 400, 400);
            }    
            
            self.tableView.backgroundView.alpha = 0;
            self.tableView.backgroundColor = [UIColor clearColor];
            
        }else{
            
//            UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.frame]; 
//            backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login.png"]];
//            
//            self.tableView.backgroundView = backgroundView; 
            self.tableView.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
            
//            [backgroundView release];
            [[NSNotificationCenter defaultCenter] addObserver:self 
                                                     selector:@selector(keyboardWillShow:) 
                                                         name:UIKeyboardWillShowNotification 
                                                       object:nil];
            
            [[NSNotificationCenter defaultCenter] addObserver:self 
                                                     selector:@selector(keyboardWillHide:) 
                                                         name:UIKeyboardWillHideNotification 
                                                       object:nil];	   
        }   

        

        
    }
    return self;
}

- (void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    TT_RELEASE_SAFELY(_usernameField);
    TT_RELEASE_SAFELY(_passwordField);  
    TT_RELEASE_SAFELY(_rememberMeSwitch); 
    TT_RELEASE_SAFELY(_versionLabel); 
    TT_RELEASE_SAFELY(_hostField); 
    TT_RELEASE_SAFELY(_portField); 
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)loadView
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [super loadView];
    
    [self.view addSubview:self.versionLabel];
}


- (void)viewDidLoad
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

}

- (void)viewDidUnload
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    TT_RELEASE_SAFELY(_usernameField);
    TT_RELEASE_SAFELY(_passwordField);  
    TT_RELEASE_SAFELY(_rememberMeSwitch); 
    TT_RELEASE_SAFELY(_versionLabel); 
    TT_RELEASE_SAFELY(_hostField); 
    TT_RELEASE_SAFELY(_portField); 
}

- (void)viewWillAppear:(BOOL)animated{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    [[XMPPClient sharedInstance] disconnect];
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
    //self.tableView.scrollEnabled = NO; 
    if (TTIsPad()) {
        if (UIInterfaceOrientationIsLandscape(TTInterfaceOrientation())) {
            self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Landscape.png"]];
            
            self.tableView.frame = CGRectMake(400, 50, 400, 400);
            
        }else{
            self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Portrait.png"]];
            self.tableView.frame = CGRectMake(300, 200, 400, 400);
        }            
    }   
    [super viewWillAppear:animated];
    
    self.usernameField.text = [[NSUserDefaults standardUserDefaults] stringForKey:kJID];
    
    self.rememberMeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey: kRememberMe];
    if(_rememberMeSwitch.on){
        self.passwordField.text =[[NSUserDefaults standardUserDefaults] stringForKey:kPassword];
        
    }    
    
    self.hostField.text = [[NSUserDefaults standardUserDefaults] stringForKey:kHost];
    
    self.portField.text = [[NSUserDefaults standardUserDefaults] stringForKey:kPort];
    
    [[[XMPPClient sharedInstance]xmppStream] addDelegate: self delegateQueue:dispatch_get_main_queue()];
}

- (void)viewWillDisappear:(BOOL)animated{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    [[self navigationController] setNavigationBarHidden:NO animated:NO];
    [[[XMPPClient sharedInstance]xmppStream] removeDelegate: self];
    [super viewWillDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
    if (TTIsPad()) {
        return YES;
        
    } else {
        return interfaceOrientation == UIInterfaceOrientationPortrait;
    }

    
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (TTIsPad()) {
        if (UIInterfaceOrientationIsLandscape(TTInterfaceOrientation())) {
            self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Landscape.png"]];
            
            self.tableView.frame = CGRectMake(400, 50, 400, 400);
            
        }else{
            self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Login-Portrait.png"]];
            self.tableView.frame = CGRectMake(300, 200, 400, 400);
        }            
    }    
    
}



#pragma mark - Fields

- (UITextField *)usernameField
{
	if (_usernameField == nil)
	{
        _usernameField = [[UITextField alloc] init];
        
        //_usernameField.font = TTSTYLEVAR(font);
        _usernameField.placeholder = @"<请输入登录用户>";		
        
		_usernameField.autocorrectionType = UITextAutocorrectionTypeNo;	
        _usernameField.keyboardType = UIKeyboardTypeDefault;	
		_usernameField.returnKeyType = UIReturnKeyDone;
		
		_usernameField.clearButtonMode = UITextFieldViewModeAlways;	
		_usernameField.delegate = self;		
		[_usernameField setAccessibilityLabel:@"用户"];
	}	
	return _usernameField;
}

- (UITextField *)passwordField
{
	if (_passwordField == nil)
	{
        _passwordField = [[UITextField alloc] init];
        
        //_passwordField.font = TTSTYLEVAR(font);
        _passwordField.placeholder = @"<请输入登录密码>";		
        
		_passwordField.autocorrectionType = UITextAutocorrectionTypeNo;	
        _passwordField.keyboardType = UIKeyboardTypeDefault;	
		_passwordField.returnKeyType = UIReturnKeyDone;
		_passwordField.secureTextEntry = TRUE;
        
		_passwordField.clearButtonMode = UITextFieldViewModeAlways;		
		_passwordField.delegate = self;		
		[_passwordField setAccessibilityLabel:@"密码"];
	}	
	return _passwordField;
}

- (UITextField *)hostField
{
	if (_hostField == nil)
	{
        _hostField = [[UITextField alloc] init];
        
        _hostField.placeholder = @"<自动查找服务器>";		
        
		_hostField.autocorrectionType = UITextAutocorrectionTypeNo;	
        _hostField.keyboardType = UIKeyboardTypeDefault;	
		_hostField.returnKeyType = UIReturnKeyDone;
		
		_hostField.clearButtonMode = UITextFieldViewModeAlways;	
		_hostField.delegate = self;		
		[_hostField setAccessibilityLabel:@"服务器"];
	}	
	return _hostField;
}

- (UITextField *)portField
{
	if (_portField == nil)
	{
        _portField = [[UITextField alloc] init];
        
        
        _portField.placeholder = @"<自动查找端口>";		
        
		_portField.autocorrectionType = UITextAutocorrectionTypeNo;	
        _portField.keyboardType = UIKeyboardTypeDefault;	
		_portField.returnKeyType = UIReturnKeyDone;
		_portField.clearButtonMode = UITextFieldViewModeAlways;	
		_portField.delegate = self;		
		[_portField setAccessibilityLabel:@"端口"];
	}	
	return _portField;
}

- (UISwitch *)rememberMeSwitch
{
	if (_rememberMeSwitch == nil)
	{
        _rememberMeSwitch = [[UISwitch alloc] init];
	}	
	return _rememberMeSwitch;
}


- (UILabel *)versionLabel
{
	if (_versionLabel == nil)
	{
        _versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.height - 30,
                                                                  self.view.width, 20)];
        
        _versionLabel.font = TTSTYLEVAR(font);
        _versionLabel.textColor = TTSTYLEVAR(versionColor);
        _versionLabel.backgroundColor = [UIColor clearColor];
        _versionLabel.textAlignment = UITextAlignmentCenter;
        _versionLabel.autoresizingMask =
        UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
        _versionLabel.text = [NSString stringWithFormat:@"© 2011 Gildata Inc. v%@(%@)",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
        
	}	
	return _versionLabel;
}

#pragma mark - Actions;
- (void) loginAction
{
    
    if (!TTIsStringWithAnyText(_usernameField.text)) {
        TTAlert(@"请输入登录用户");
        return;
    }
    if (!TTIsStringWithAnyText(_passwordField.text)) {
        TTAlert(@"请输入登录密码");
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    if(TTIsStringWithAnyText(_hostField.text)){
        [[NSUserDefaults standardUserDefaults] setObject:_hostField.text forKey:kHost];
    }else{
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kHost];
    }
    if(TTIsStringWithAnyText(_portField.text)){
        [[NSUserDefaults standardUserDefaults] setObject:_portField.text forKey:kPort];
    }else{
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPort];
    }  
    
    if ([[XMPPClient sharedInstance] connectWithJID:_usernameField.text AndPassword:_passwordField.text]) {
        
        
        [[NSUserDefaults standardUserDefaults] setObject:_usernameField.text forKey:kJID];
        
        [[NSUserDefaults standardUserDefaults] setBool:self.rememberMeSwitch.on forKey:kRememberMe];
        if (self.rememberMeSwitch.on){
            [[NSUserDefaults standardUserDefaults] setObject:_passwordField.text forKey:kPassword];
        }else{
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPassword];
        }
        
    
        
    }else{
        
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if (textField == _portField ){
        NSRegularExpression *regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[0-9]*$" options:NSRegularExpressionCaseInsensitive error:nil];   
        NSUInteger numberofMatch = [regularExpression numberOfMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length)];  
        
        [regularExpression release];
        
        if(numberofMatch > 0)
        {
            
            DDLogVerbose(@"%@ isNumbericString: YES", string); 
            
            return YES;
        }
        
        DDLogVerbose(@"%@ isNumbericString: NO", string); 
        return NO;        
        
    }else{
        return YES;
    }
}

#pragma mark - TTModelViewController
- (void)createModel {
    self.dataSource = [TTSectionedDataSource dataSourceWithObjects:
                       @"",                                         
                       [TTTableControlItem itemWithCaption:@"登录用户" control:self.usernameField],
                       [TTTableControlItem itemWithCaption:@"登录密码" control:self.passwordField],
                       [TTTableControlItem itemWithCaption:@"记住密码" control:self.rememberMeSwitch], 
                       @"",
                       [TTTableButton itemWithText:@"登录" delegate:self selector:@selector(loginAction)],
                       @"服务器设置",                                         
                       [TTTableControlItem itemWithCaption:@"主机" control:self.hostField],
                       [TTTableControlItem itemWithCaption:@"端口" control:self.portField],
                       nil];    
    
}


#pragma mark - UIKeyboardNotifications
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
    DDLogVerbose(@"%@: %@ %@", THIS_FILE, THIS_METHOD, note);
	CGRect keyboardBeginFrame;
    CGRect keyboardEndFrame;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBeginFrame];
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardEndFrame];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    
    
	// get a rect for the textView frame
    CGRect viewFrame = self.view.frame;
    viewFrame.size.height -=  keyboardEndFrame.size.height;
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	self.tableView.frame = viewFrame;
    [self.tableView scrollFirstResponderIntoView];    
    
	// commit animations
	[UIView commitAnimations];

    

}

-(void) keyboardWillHide:(NSNotification *)note{
    DDLogVerbose(@"%@: %@ %@", THIS_FILE, THIS_METHOD, note);
    
	CGRect keyboardBeginFrame;
    CGRect keyboardEndFrame;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBeginFrame];
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardEndFrame];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
	// get a rect for the textView frame
    CGRect viewFrame = self.view.frame;
    //viewFrame.size.height += (keyboardEndFrame.origin.y-keyboardBeginFrame.origin.y);
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	self.tableView.frame = viewFrame;
    
	// commit animations
	[UIView commitAnimations];
}


- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
    [[TTNavigator navigator] removeAllViewControllers];
    TTOpenURL(@"gabber://root");  

}

- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
    TTAlert(@"登录失败"); 

    
}

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
    //TTAlert([NSString stringWithFormat:@"发生错误：%@",error.localizedDescription]);  
}


@end
